package com.idea.relax.launch.autoconfig;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

/**
 * @author: 沉香
 * @date: 2023/4/14
 * @description:
 */
@Configuration(
	proxyBeanMethods = false
)
public class ServerUtil implements SmartInitializingSingleton {

	private static ServerProperties serverProperties;

	private static String hostName;

	private static String ip;

	private static Integer port;

	private static String appName;

	private static String env;


	@Autowired(
		required = false
	)
	public ServerUtil(ServerProperties serverProperties, Environment environment) {
		ServerUtil.serverProperties = serverProperties;
		ServerUtil.appName = environment.getProperty("spring.application.name", "");
		ServerUtil.env = StringUtil.join(environment.getActiveProfiles());
		ServerUtil.port = serverProperties.getPort();
	}

	@Override
	public void afterSingletonsInstantiated() {
		ServerUtil.hostName = INetUtil.getHostName();
		ServerUtil.ip = INetUtil.getHostIp();
		ServerUtil.port = serverProperties.getPort();
	}


	/**
	 * 判断是否为本地开发环境
	 *
	 * @return boolean
	 */
	public static boolean isLocalProfile() {
		String osName = System.getProperty("os.name");
		return StringUtils.hasText(osName) && !("LINUX".equals(osName));
	}


	public static ServerMetadata getServerMetadata() {
		ServerMetadata serverMetadata = new ServerMetadata();
		String serverIp = (ip == null ? INetUtil.getHostIp() : ip);
		Integer serverPort = (port == null ? serverProperties.getPort() : port);
		serverMetadata.setIp(serverIp);
		serverMetadata.setEnv(env);
		serverMetadata.setHostName(hostName == null ? INetUtil.getHostName() : hostName);
		serverMetadata.setPort(serverPort);
		serverMetadata.setAppName(appName);
		serverMetadata.setServerAddr(serverIp + ":" + serverPort);
		return serverMetadata;
	}


	public static ServerProperties getServerProperties() {
		return serverProperties;
	}

}
